package com.msh.business;

import com.msh.annotations.ProcessType;
import com.msh.common.VMSystem;
import com.msh.contract.StatusInfo;
import com.msh.contract.VmStatusContract;
import com.msh.exception.LogicException;
import com.msh.feignService.VMService;
import com.msh.http.viewModel.TaskViewModel;
import com.msh.service.TaskService;
import com.msh.utils.JsonUtil;
import com.msh.viewmodel.VendingMachineViewModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author :zhangchuanfu
 * @Date :2023/1/12
 * @Time :20:58
 * @description :
 */
@Component
@ProcessType("vmStatus")
@Slf4j
public class VMStatusHandler implements MsgHandler{
    @Autowired
    private TaskService taskService;
    @Autowired
    private VMService vmService;
    @Override
    public void process(String jsonMsg) throws IOException {
        //解析报文
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null || vmStatusContract.getStatusInfo() == null || vmStatusContract.getStatusInfo().size() <= 0) return;
        //判断报文中，状态如果有一个是false，创建维修工单
        if (vmStatusContract.getStatusInfo().stream().allMatch(StatusInfo::isStatus)) return;
        try {
            //根据设备编号查询设备
            VendingMachineViewModel vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());

            //获得同区域内工单最少的人
            Integer assignnorId = taskService.getLeastuser(vmInfo.getRegionId(),true);
            TaskViewModel task = new TaskViewModel();
            task.setUserId(1);//自动创建工单的默认执行人
            task.setAssignorId(assignnorId);//指派id
            task.setCreateType(0);//自动创建
            task.setDesc("自动维修工单");
            task.setInnerCode(vmStatusContract.getInnerCode());
            task.setProductType(VMSystem.TASK_TYPE_REPAIR);

            taskService.createTask(task);//创建工单
        } catch (LogicException e) {
            e.printStackTrace();
            log.error("创建自动维修工单失败 msg is :" + jsonMsg);
        }
    }
}
